<template>
    <!-- 虚拟商品订单确认 -->
    <view class="confirm-main">
        <view class="confirm-content">
            <view class="goods">
                <GoodsCard
                    v-for="(item, index) in Data.goodsList"
                    :orderType="6"
                    :key="`k${index}`"
                    :showGoodsTag="true"
                    :goodsData="item" />
            </view>
            <view class="other-info">
                <view class="other-info-item">
                    <view>商品总价</view>
                    <view class="other-info-item-right">
                        <text v-if="Data.sellAmount > 0">{{ floatDivide(Data.sellAmount, 100) }}元+</text>
                        <text>{{ floatDivide(Data.totalPoints, 100) }}积分 </text>
                    </view>
                </view>
                <view class="other-info-item">
                    <view>积分抵扣</view>
                    <view class="other-info-item-right price">
                        <text> -{{ floatDivide(Data.totalPoints, 100) }}积分 </text>
                    </view>
                </view>
            </view>
            <view @click="showPopup('remark')" class="remark">
                <view class="remark-label">备注</view>
                <view>
                    <text class="remark-content" v-if="Data.remarks">{{ Data.remarks }}</text>
                    <text class="remark-content-none" v-else>暂无备注</text>
                    <image class="cell-icon-img ver-top" :src="getImgOssUrl('/ui-prod-2.0.0/icon_img05.png')" />
                </view>
            </view>
        </view>
        <view class="pay-footer">
            <view class="pay-footer-info">
                <view>
                    <text class="pay-footer-info-text">应付</text>
                    <text class="pay-footer-info-price"
                        ><text class="pay-footer-info-icon">￥</text
                        >{{ floatDivide(Data.confirmInfo.orderAmountTotal, 100) }}
                    </text>
                </view>
                <view class="pay-button" @click="beforePayValide"> 提交订单 </view>
            </view>
        </view>
        <uni-popup type="bottom" ref="popup" :safe-area="false">
            <view class="popup-bg">
                <image
                    class="close-img"
                    @click="popup.close()"
                    :src="getImgOssUrl('/ui-prod-2.0.0/cancel_1.1.png')"></image>
                <view class="popup-title">{{ popupData.title }}</view>
                <view v-if="popupData.type === 'remark'">
                    <textarea
                        class="remark-text"
                        placeholder="请填写备注信息，不超过200字"
                        v-model="popupData.remark"
                        maxlength="200" />
                </view>
                <view class="popup-btn" @click="closePopup(popupData.type)">确定</view>
            </view>
        </uni-popup>
        <!-- 库存不足取消订单 -->
        <MessageBox
            ref="messagebox"
            :content="Dialog.content"
            btnName="取消订单"
            @comfirm="cancelOrderConfirm"></MessageBox>
        <Loading />
    </view>
</template>
<script setup>
import { ref, reactive, computed, inject } from 'vue';
import { floatDivide, floatMultiply, getImgOssUrl } from '@/commons/utils.js';
import request from '@/request';
import router from '@/router';
import store from '@/store';
import storage from '@/commons/storage';
import Loading from '@/components/el-loading';
import { useTrace } from '@/commons/trace';
import subscribe from '@/commons/subscribe';
import GoodsCard from '@/components/goodsCard';
import MessageBox from '@/components/messageBox';

const { traceReport } = useTrace();

const props = defineProps({
    quantity: {
        type: Number,
        default: 1
    },
    goodsId: {
        type: [String, Number]
    },
    goodsType: {
        type: [String, Number]
    }
});

const currency = inject('currency');

const Data = reactive({
    confirmInfo: {},
    goodsList: [],
    orderSn: '',
    orderId: '',
    remarks: ''
});

const messagebox = ref();
const Dialog = reactive({
    content: ''
});

// 弹出框
const popup = ref();
const popupData = reactive({
    title: '',
    type: '',
    hidePoint: '',
    remark: ''
});

const rebuildSkuList = (arr = []) => {
    return arr.map(x => {
        return Object.assign(x, {
            goodsNum: x.quantity,
            goodsPrice: x.skuPrice,
            goodPoints: x.points
        });
    });
};

const getConfirm = async () => {
    let params = {
        goodsId: props.goodsId,
        quantity: props.quantity,
        goodsType: props.goodsType
    };
    let res = await request('confirmVirtualOrderServ', params);
    Data.confirmInfo = res.data;
    Data.sellAmount = res.data.skuList[0].sellAmount;
    Data.totalPoints = res.data.skuList[0].totalPoints;
    Data.goodsList = rebuildSkuList(res.data.skuList);
};
getConfirm();

// 打开弹框
const showPopup = type => {
    popupData.type = type;
    switch (type) {
        case 'remark':
            popupData.title = '订单备注';
            popupData.remark = Data.remarks;
            break;
        default:
            break;
    }
    popup.value.open();
};

// 点击确认关闭弹框
const closePopup = type => {
    switch (type) {
        case 'remark':
            Data.remarks = popupData.remark;
            break;
        default:
            break;
    }
    popup.value.close();
};

let orderFlag = ref(false);
let firstSubmit = ref(1);
const beforePayValide = () => {
    let stopOrder = null;
    let timeId = null;
    if (firstSubmit.value === 1) {
        firstSubmit.value++;
        orderFlag.value = true;
        payValide();
        stopOrder = setInterval(() => {
            clearInterval(stopOrder);
            orderFlag.value = false;
        }, 5000);
    } else {
        if (orderFlag.value) {
            uni.showToast({
                title: '订单提交中...',
                icon: 'none'
            });
            return;
        }
        orderFlag.value = true;
        payValide();
        timeId = setInterval(() => {
            clearInterval(timeId);
            orderFlag.value = false;
        }, 5000);
    }
};

const orderSubmit = async () => {
    let params = Object.assign(
        {
            buyerRemarks: Data.remarks,
            goodsType: props.goodsType
        },
        Data.confirmInfo.skuList[0]
    );
    try {
        let res = await request('ordeVirtualrCommitServ', params);
        Data.orderSn = res.data.orderSn;
        Data.orderId = res.data.orderId;
        if (Data.orderId) {
            /***************埋点代码开始********************/
            const traceGoodsList = [];
            Data.goodsList.map(item => {
                traceGoodsList.push({
                    productId: item.goodsId,
                    productName: item.goodsName,
                    skuId: item.skuId,
                    goodsPrice: item.skuPrice,
                    goodsNumber: item.quantity
                });
            });
            traceReport('submit_order', {
                orderId: Data.orderId,
                // 该金额现在用的是实付金额字段，以后需要有个用于表示GMV的字段替换
                orderAmount: Data.confirmInfo.orderAmountTotal,
                payAccount: Data.confirmInfo.orderAmountTotal,
                payResult: '',
                goods: traceGoodsList
            });
            /***************埋点代码结束********************/
            if (Data.confirmInfo.orderAmountTotal > 0) {
                payChannelList();
            } else {
                let query = {};
                router.redirectTo({
                    url: `/pages-cart/paystatus/index?orderId=${Data.orderId}&type=1`
                });
            }
        }
        if (res.data && res.data.length) {
            let info = res.data.find(el => el.errorMsg) || {};
        }
    } catch (e) {
        uni.showToast({
            title: e.data.msg,
            icon: 'none'
        });
        getConfirm();
    }
};

const payChannelList = async () => {
    let res = await request('payChannelListServ');
    let payChannel = res.data.payList?.[0];
    wxPay(payChannel);
    /***************埋点代码开始********************/
    traceReport('pay_order', {
        orderId: Data.orderId,
        payAccount: Data.confirmInfo.orderAmountTotal,
        payResult: ''
    });
    /***************埋点代码结束********************/
};
const payValide = async () => {
    await subscribe('order_payment');
    orderSubmit();
};
const wxPay = async val => {
    let params = {
        orderSn: Data.orderSn,
        payMethod: val.type
    };
    let res;
    try {
        res = await request('payPrepayServ', params);
    } catch (err) {
        orderFlag.value = false;
        if ([9002110, 9002109].includes(err.data?.code)) {
            Dialog.content = err.data?.msg || '网络错误，请稍后重试~';
            messagebox.value.openPopup();
        } else {
            uni.showToast({
                title: err.data?.msg || '网络错误，请稍后重试~',
                icon: 'none',
                duration: 2000
            });
        }
        return;
    }
    let obj = res.data || {};
    // isPaymentApp=true: 商户绑定了支付小程序且开通了宝付支付
    if (res.data?.isPaymentApp) {
        router.redirectTo({
            url: `/pages-cart/cashier/index?appId=${obj.appId}&amount=${Data.confirmInfo.orderAmountTotal}&orderSn=${Data.orderSn}&payMethod=${val.type}&orderId=${Data.orderId}&orderType=6&type=2`
        });
    } else {
        uni.requestPayment({
            provider: 'wxpay',
            timeStamp: obj.timeStamp,
            nonceStr: obj.nonceStr,
            package: obj.package,
            signType: obj.signType,
            paySign: obj.paySign,
            success: function (res) {
                router.redirectTo({
                    url: `/pages-cart/paystatus/index?orderId=${Data.orderId}&orderType=6`
                });
            },
            fail: async err => {
                await request('payCancelServ', { orderSn: Data.orderSn, payMethod: val.type });
                if (err.errMsg == 'requestPayment:fail cancel') {
                    uni.showModal({
                        content: '是否放弃本次付款？',
                        cancelText: '稍后付款',
                        confirmText: '继续付款',
                        confirmColor: '#FE292B',
                        success: async res => {
                            if (res.cancel) {
                                await subscribe('order_non_payment');
                                router.redirectTo({
                                    url: `/pages-user/orderdetail/index?orderId=${Data.orderId}`
                                });
                            }
                            if (res.confirm) {
                                wxPay(val);
                            }
                        }
                    });
                } else {
                    router.redirectTo({
                        url: `/pages-cart/paystatus/index?orderId=${Data.orderId}&type=2`
                    });
                }
            }
        });
    }
};

const cancelOrderConfirm = async () => {
    /*************埋点代码开始***********************/
    const traceGoodsList = [];
    Data.goodsList.map(item => {
        traceGoodsList.push({
            productId: item.goodsId,
            productName: item.goodsName,
            skuId: item.skuId
        });
    });
    traceReport('cancel_order', {
        orderId: Data.orderId,
        goods: traceGoodsList
    });
    /*************埋点代码结束***********************/
    const res = await request('orderCancelServ', {
        shopId: uni.getStorageSync('ZW_SHOP_ID'),
        orderId: Data.orderId
    });
    if (res.data) {
        messagebox?.value?.closePopup();
        router.redirectTo({
            url: `/pages-user/orderdetail/index?orderId=${Data.orderId}`
        });
    }
};
</script>
<style lang="scss" scoped src="./style.scss"></style>
